package net.common.manager;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import com.naire.modul.dictionary.vo.DictionaryVo;
import com.naire.modul.dictype.service.DictypeSearchService;
import com.naire.modul.dictype.vo.DictypeVo;

/**
 * 字典管理
 *
 */
public class DictManager {

	private static Map<String, Map<String, DictionaryVo>> DICTSORT = new TreeMap<String, Map<String, DictionaryVo>>();
	private static Map<String, DictionaryVo> DICT = new HashMap<String, DictionaryVo>();

	/**
	 * 数据字典初始化
	 * 
	 */
	public static void init() {
		initDictSort();
	}

	/**
	 * 初始化字典分类
	 * 
	 */
	private static void initDictSort() {
		DictypeSearchService service = new DictypeSearchService();
		try {
			service.invoke();
			List<DictypeVo> list = service.getList();
			for(DictypeVo v : list) {
				Map<String, DictionaryVo> p = new TreeMap<String, DictionaryVo>();
				DICTSORT.put(v.getSort_num(), p);
				for(DictionaryVo dv : v.getVos()) {
					p.put(dv.getDict_num(), dv);
					DICT.put(dv.getDict_num(), dv);
				}
				v.setVos(null);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void set(String key, DictionaryVo vo) {
		synchronized (DICTSORT) {			
			Map<String, DictionaryVo> maps = DICTSORT.get(key);
			maps.put(vo.getDict_num(), vo);
			DICT.put(vo.getDict_num(), vo);
		}
	}
	
	public static void remove(String key, DictionaryVo vo) {
		Map<String, DictionaryVo> maps = DICTSORT.get(key);
		maps.remove(vo.getDict_num());
		DICT.remove(vo.getDict_num());
	}
	
	public static Collection<DictionaryVo> get(String key) {
		Map<String, DictionaryVo> maps = DICTSORT.get(key);
		if(maps != null) {			
			return maps.values();
		} else {
			return null;
		}
	}
	
	public static List<DictionaryVo> getValues(String key) {
		List<DictionaryVo> list = new ArrayList<DictionaryVo>(get(key));
		return list;
	}
	
	public static String getValue(String key, String val) {
		DictionaryVo v = getObject(key, val);
		return v.getDict_name();
	}
	
	public static String getValue(String val) {
		DictionaryVo v = getObject(val);
		return v.getDict_name();
	}
	
	public static DictionaryVo getObject(String val) {
		DictionaryVo v = DICT.get(val);
		return v;
	}
	
	public static DictionaryVo getObject(String key, String val) {
		Map<String, DictionaryVo> maps = DICTSORT.get(key);
		DictionaryVo v = maps.get(val);
		return v;
	}
}
